from models.user import User
from models import db


class UserService:
    def __init__(self, user_model):
        self.user_model = user_model

    def get_all_users(self):
        """获取所有用户"""
        return self.user_model.query.all()

    def get_user_by_id(self, user_id):
        """根据ID获取用户"""
        return self.user_model.query.get(user_id)

    def create_user(self, name, email, password):
        """创建新用户"""
        # 检查邮箱是否已存在
        if self.user_model.query.filter_by(email=email).first():
            raise ValueError("邮箱已存在")

        user = self.user_model(name=name, email=email)
        user.password = password
        
        # 检查是否是第一个用户，如果是则设为管理员
        if self.user_model.query.count() == 0:
            user.is_admin = True
            
        db.session.add(user)
        db.session.commit()
        return user

    def update_user(self, user_id, name, email):
        """更新用户信息"""
        user = self.user_model.query.get(user_id)
        if not user:
            raise ValueError("用户未找到")

        # 检查邮箱是否已存在（排除当前用户）
        existing_user = self.user_model.query.filter_by(email=email).first()
        if existing_user and existing_user.id != user_id:
            raise ValueError("邮箱已存在")

        user.name = name
        user.email = email
        db.session.commit()
        return user

    def delete_user(self, user_id):
        """删除用户"""
        user = self.user_model.query.get(user_id)
        if not user:
            raise ValueError("用户未找到")
        
        # 检查是否是管理员，管理员不能被删除
        if user.is_admin:
            raise ValueError("管理员用户不能被删除")

        db.session.delete(user)
        db.session.commit()
        
    def authenticate_user(self, email, password):
        """验证用户登录"""
        user = self.user_model.query.filter_by(email=email).first()
        if user and user.verify_password(password):
            return user
        return None
        
    def change_password(self, user_id, new_password):
        """修改用户密码"""
        user = self.user_model.query.get(user_id)
        if not user:
            raise ValueError("用户未找到")
            
        user.password = new_password
        db.session.commit()
        return user